package com.mls.fivedistrict.server.impl;

import com.github.pagehelper.PageHelper;
import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.dao.UserAuthMapper;
import com.mls.fivedistrict.dao.UserAuthRecordMapper;
import com.mls.fivedistrict.pojo.User;
import com.mls.fivedistrict.pojo.UserAuthRecord;
import com.mls.fivedistrict.pojo.UserAuthRecordExample;
import com.mls.fivedistrict.server.UserAuthRecordService;
import com.mls.fivedistrict.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created by chenxiuxiang on 2018/4/10.
 */
@Service("userAuthRecordService")
public class UserAuthRecordServiceImpl implements UserAuthRecordService {

    @Autowired
    UserAuthRecordMapper userAuthRecordMapper;
    @Autowired
    UserService userService;

    @Override
    public int addAuthRecord(UserAuthRecord authRecord) {
        int i = userAuthRecordMapper.insertSelective(authRecord);
        return i;
    }

    @Override
    public List<UserAuthRecord> getUserAuthRecord(PageFilter pageFilter) {
        UserAuthRecordExample userAuthRecordExample = new UserAuthRecordExample();
        UserAuthRecordExample.Criteria criteria = userAuthRecordExample.createCriteria();
        Map<String, String> filterMap = pageFilter.getFilterMap();
        String phone = filterMap.get("phone");
        if (!StringUtils.isEmpty(phone)) {
            User userByPhone = userService.getUserByPhone(phone);
            if (userByPhone != null) {
                criteria.andUserIdEqualTo(userByPhone.getId());
            }
        }
        Optional.ofNullable(filterMap.get("realName")).map(realName -> criteria.andRealNameLike("%" + realName + "%"));
        Optional.ofNullable(filterMap.get("cardNo")).map(cardNo -> criteria.andCradNoLike("%" + cardNo + "%"));
        Optional.ofNullable(filterMap.get("startDate")).map(startDate -> criteria.andCreateDateGreaterThanOrEqualTo(new Date(Long.valueOf(startDate))));
        Optional.ofNullable(filterMap.get("endDate")).map(endDate -> criteria.andCreateDateLessThanOrEqualTo(new Date(Long.valueOf(endDate))));
        Optional.ofNullable(filterMap.get("userAuthId")).map(userAuthId -> criteria.andAuthIdEqualTo(Long.valueOf(userAuthId)));
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        userAuthRecordExample.setOrderByClause("create_date desc ");
        List<UserAuthRecord> userAuthRecords = userAuthRecordMapper.selectByExample(userAuthRecordExample);
        return userAuthRecords;
    }

}
